package main

import (
	"fmt"
	"log"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 定义模型
type User struct {
	gorm.Model
	Name      string
	Addresses []Address `gorm:"foreignKey:UserID"`
	Orders    []Order   `gorm:"foreignKey:UserID"`
}

type Address struct {
	gorm.Model
	UserID uint
	Street string
	City   string
}

type Order struct {
	gorm.Model
	UserID  uint
	OrderID string
	Amount  float64
}

func main() {
	// 设置MySQL连接字符串
	dsn := "root:root@tcp(127.0.0.1:3307)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		log.Fatal("failed to connect database")
	}

	// 自动迁移模式，创建表
	db.AutoMigrate(&User{}, &Address{}, &Order{})

	// 创建用户
	user := User{Name: "John Doe"}
	db.Create(&user)

	// 创建地址
	address1 := Address{UserID: user.ID, Street: "123 Main St", City: "Anytown"}
	address2 := Address{UserID: user.ID, Street: "456 Elm St", City: "Othertown"}
	db.Create(&address1)
	db.Create(&address2)

	// 创建订单
	order1 := Order{UserID: user.ID, OrderID: "ORD001", Amount: 100.00}
	order2 := Order{UserID: user.ID, OrderID: "ORD002", Amount: 200.00}
	db.Create(&order1)
	db.Create(&order2)

	// 查询用户，并预加载地址和订单信息
	var userWithDetails User
	preloads := []string{"Addresses", "Orders"}
	db = db.Debug() // 开启调试模式
	for _, preload := range preloads {
		db = db.Preload(preload)
	}
	db.First(&userWithDetails, user.ID) // 假设我们通过ID查询用户

	// 输出结果
	fmt.Printf("User: %+v\n", userWithDetails)
	for _, address := range userWithDetails.Addresses {
		fmt.Printf("Address: %+v\n", address)
	}
	for _, order := range userWithDetails.Orders {
		fmt.Printf("Order: %+v\n", order)
	}
}
